﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;

namespace CustomerContactSystem.WebForms.Admin.Users
{
    public partial class Edit : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            GetDepartments();
            GetGroups();
            GetRoles();
            GetUser();
        }

        private void GetDepartments()
        {
            var departments = DepartmentRepository.QueryOver().OrderBy(d => d.DepartmentName).Asc.List();
            BindDropDownList(DepartmentList, departments, "DepartmentName", "Id", "--Select--", "0");
        }

        private void GetGroups()
        {
            var groups = UserGroupRepository.QueryOver().OrderBy(u => u.GroupName).Asc.List();
            BindDropDownList(GroupList, groups, "GroupName", "Id", "--Select--", "0");
        }

        private void GetRoles()
        {
            var roles = UserRoleRepository.QueryOver().OrderBy(r => r.RoleName).Asc.List();
            RoleList.DataSource = roles;
            RoleList.DataBind();
        }

        private void GetUser() {
            var userId = int.Parse(Request.QueryString["id"]);
            var user = UserRepository.GetById(userId);

            if (user == null) {
                return;
            }

            DepartmentList.SelectedIndex =
                DepartmentList.Items.IndexOf(
                    DepartmentList.Items.FindByValue(user.Department.Id.ToString(CultureInfo.InvariantCulture)));
            GroupList.SelectedIndex =
                GroupList.Items.IndexOf(
                    GroupList.Items.FindByValue(user.UserGroup.Id.ToString(CultureInfo.InvariantCulture)));
            DisplayName.Text = user.DisplayName;
            Email.Text = user.Email;
            Username.Text = user.Username;
            Password.Text = user.Password;           
            FrontLine.Checked = user.FirstPointOfContact;
            AreaCovered.Text = user.AreaCovered;
            IsActive.Checked = user.IsActive;

            var roles = user.Roles.Select(role => role.RoleName).ToList();

            foreach (RepeaterItem ri in RoleList.Items)
            {
                if (ri.ItemType != ListItemType.Item && ri.ItemType != ListItemType.AlternatingItem)
                {
                    continue;
                }
                var chk = (CheckBox)ri.FindControl("RoleChk");
                if (chk == null)
                {
                    continue;
                }

                if (roles.Contains(chk.Text))
                {
                    chk.Checked = true;
                }
            }
        }

        protected void SaveUserClick(object sender, EventArgs e)
        {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            var userId = int.Parse(Request.QueryString["id"]);
            var user = UserRepository.GetById(userId);

            if (user == null)
            {
                return;
            }

            var department = DepartmentRepository.LoadReference(int.Parse(DepartmentList.SelectedItem.Value));
            var userGroup = UserGroupRepository.LoadReference(int.Parse(GroupList.SelectedItem.Value));
            user.Department = department;
            user.UserGroup = userGroup;
            user.DisplayName = DisplayName.Text;
            user.Email = Email.Text;
            user.Username = Username.Text;
            user.Password = Password.Text;
            user.PasswordMatch = Password.Text;
            user.FirstPointOfContact = FrontLine.Checked;
            user.AreaCovered = AreaCovered.Text;
            user.IsActive = true;

            if (!IsValidObject(user, ErrorMsg))
            {
                return;
            }

            foreach (RepeaterItem ri in RoleList.Items)
            {
                if (ri.ItemType != ListItemType.Item && ri.ItemType != ListItemType.AlternatingItem)
                {
                    continue;
                }
                var chk = (CheckBox)ri.FindControl("RoleChk");
                var role = UserRoleRepository.QueryOver().Where(r => r.RoleName == chk.Text).SingleOrDefault();
                if (role == null) {
                    continue;
                }
                if (chk.Checked) {
                    user.AddRole(role);
                }
                else {
                    user.RemoveRole(role);
                }
            }

            UserRepository.Update(user);
            Response.Redirect("~/Admin/Users/List.aspx#" + user.Id);
        }
    }
}